﻿using ezCloud.Api.Models;
using ezCloud.Data;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;

namespace ezCloud.Api.Common
{
    public class Notification
    {
        public static async Task addNotificationToken(string uid, string token, string type)
        {
            if (token != null && type != null)
            {
                using (var client = new HttpClient())
                {
                    // New code:
                    client.BaseAddress = new Uri(ConfigurationManager.AppSettings["notification_server"]);
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "key=" + ConfigurationManager.AppSettings["notification_server_key"]);

                    var postData = new
                    {
                        uid = uid,
                        type = type,
                        token = token
                    };
                    HttpResponseMessage response = await client.PostAsJsonAsync("register/" + ConfigurationManager.AppSettings["notification_server_clientid"], postData);
                    if (response.IsSuccessStatusCode)
                    {

                    }
                }

            }
        }

        public static async Task sendNotificationToDevice(string uid, string message, int hotelId, string HotelAppCodeName)
        {

            if (message != null && uid != null)
            {
                var context = new ezCloudDataContext();
                var checkHotelAppCodeSelected = 0;
                if (HotelAppCodeName != "ezCloudHotel")
                {
                    checkHotelAppCodeSelected = context.HotelAppConfig
                                                    .Where(h => h.HotelId == hotelId)
                                                    .Join(
                                                        context.HotelAppCode.Where(r => r.HotelAppCodeName == HotelAppCodeName),
                                                        c => c.HotelAppCodeId,
                                                        p => p.HotelAppCodeId,
                                                        (c, p) => new { c.HotelAppCodeId }
                                                        )
                                                    .Count();
                }else
                {
                    checkHotelAppCodeSelected = 1;
                }

                if (checkHotelAppCodeSelected > 0)
                {
                    using (var client = new HttpClient())
                    {

                        if (hotelId != 0)
                        {
                            var userId = context.Hotels.Where(R => R.HotelId == hotelId).Select(p => p.HotelOwnerId).FirstOrDefault();
                            var username = context.AspNetUsers.Where(US => US.Id == userId).Select(p => p.UserName).FirstOrDefault();
                            uid = username.ToString();
                        }


                        client.BaseAddress = new Uri(ConfigurationManager.AppSettings["notification_server"]);
                        client.DefaultRequestHeaders.Accept.Clear();
                        client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                        client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "key=" + ConfigurationManager.AppSettings["notification_server_key"]);

                        var postData = new
                        {
                            uid = uid,
                            data = new
                            {
                                message = message,
                                HotelAppCodeName = HotelAppCodeName
                            }
                        };
                        HttpResponseMessage response = await client.PostAsJsonAsync("send/" + ConfigurationManager.AppSettings["notification_server_clientid"], postData);
                        if (response.IsSuccessStatusCode)
                        {

                        }
                    }
                }



            }
        }

        public static async Task sendLogEmailMarketing(string uid, string message, int hotelId, string HotelAppCodeName)
        {

            if (message != null && uid != null)
            {
                var context = new ezCloudDataContext();
                var checkHotelAppCodeSelected = 0;
                if (HotelAppCodeName != "ezCloudHotel")
                {
                    checkHotelAppCodeSelected = context.HotelAppConfig
                                                    .Where(h => h.HotelId == hotelId)
                                                    .Join(
                                                        context.HotelAppCode.Where(r => r.HotelAppCodeName == HotelAppCodeName),
                                                        c => c.HotelAppCodeId,
                                                        p => p.HotelAppCodeId,
                                                        (c, p) => new { c.HotelAppCodeId }
                                                        )
                                                    .Count();
                }
                else
                {
                    checkHotelAppCodeSelected = 1;
                }

                if (checkHotelAppCodeSelected > 0)
                {
                    using (var client = new HttpClient())
                    {

                        if (hotelId != 0)
                        {
                            var userId = context.Hotels.Where(R => R.HotelId == hotelId).Select(p => p.HotelOwnerId).FirstOrDefault();
                            var username = context.AspNetUsers.Where(US => US.Id == userId).Select(p => p.UserName).FirstOrDefault();
                            uid = username.ToString();
                        }


                        client.BaseAddress = new Uri(ConfigurationManager.AppSettings["notification_server"]);
                        client.DefaultRequestHeaders.Accept.Clear();
                        client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                        client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "key=" + ConfigurationManager.AppSettings["notification_server_key"]);

                        var postData = new
                        {
                            uid = uid,
                            data = new
                            {
                                message = message,
                                HotelAppCodeName = HotelAppCodeName
                            }
                        };
                        HttpResponseMessage response = await client.PostAsJsonAsync("send/" + ConfigurationManager.AppSettings["notification_server_clientid"], postData);
                        if (response.IsSuccessStatusCode)
                        {

                        }
                    }
                }



            }
        }


        public static async Task EjectDevice(string token)
        {

            if (token != null)
            {
                using (var client = new HttpClient())
                {
                    // New code:
                    client.BaseAddress = new Uri(ConfigurationManager.AppSettings["notification_server"]);
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "key=" + ConfigurationManager.AppSettings["notification_server_key"]);

                    var postData = new
                    {
                        token = token
                    };
                    HttpResponseMessage response = await client.PostAsJsonAsync("logout/" + ConfigurationManager.AppSettings["notification_server_clientid"], postData);
                    if (response.IsSuccessStatusCode)
                    {

                    }
                }

            }
        }
        public static async Task processNotificationCheckin(UserProfile user, string RoomName)
        {
            Notification.sendNotificationToDevice(user.UserName.ToLower(), user.FullName + " Checkin " + RoomName + " ", user.HotelId, "NOTIFICATION_CHECKEDIN");
        }
        public static async Task processNotificationBooked(UserProfile user, string RoomName, int ReservationRoomNumber, string customerName, string notifi)
        {
            notifi = notifi.Replace("[USER]", user.FullName);
            notifi = notifi.Replace("[RESERVATION_NUMBER]", ReservationRoomNumber.ToString());
            notifi = notifi.Replace("[FULL_NAME]", customerName);
            notifi = notifi.Replace("[ROOM]", RoomName);
            
            Notification.sendNotificationToDevice(user.UserName.ToLower(), notifi, user.HotelId, "NOTIFICATION_BOOKED");
        }
        public static async Task processNotificationCanceled(UserProfile user, int? ReservationRoomNumber, string room_name, string customer_name, string reason, string notifi)
        {
            notifi = notifi.Replace("[USER_NAME]", user.FullName);
            notifi = notifi.Replace( "[ROOM_NAME]", room_name.ToString() );
            notifi = notifi.Replace("[RESERVATION_NUMBER]", ReservationRoomNumber.ToString());
            notifi = notifi.Replace("[CUSTOMER_NAME]", customer_name);
            notifi = notifi.Replace("[REASON]", reason);
            Notification.sendNotificationToDevice(user.UserName.ToLower(), notifi, user.HotelId, "NOTIFICATION_CANCELED");
        }
        public static async Task processNotificationCanceledNan(UserProfile user, int? ReservationRoomNumber,  string customer_name, string reason, string notifi)
        {
            notifi = notifi.Replace("[USER_NAME]", user.FullName); 
            notifi = notifi.Replace("[RESERVATION_NUMBER]", ReservationRoomNumber.ToString());
            notifi = notifi.Replace("[CUSTOMER_NAME]", customer_name);
            notifi = notifi.Replace("[REASON]", reason);
            Notification.sendNotificationToDevice(user.UserName.ToLower(), notifi, user.HotelId, "NOTIFICATION_CANCELED");
        }

        public static async Task processNotificationCanceledCm(UserProfile user, int? ReservationRoomNumber, string customer_name, string reason, string notifi)
        {
            notifi = notifi.Replace("[USER_NAME]", user.FullName);
            notifi = notifi.Replace("[RESERVATION_NUMBER]", ReservationRoomNumber.ToString());
            notifi = notifi.Replace("[CUSTOMER_NAME]", customer_name);
            notifi = notifi.Replace("[REASON]", reason);
            Notification.sendNotificationToDevice(user.UserName.ToLower(), notifi, user.HotelId, "NOTIFICATION_CANCELED");
        }

        public static async Task processNotificationCanceledGroup(UserProfile user, int? ReservationRoomNumber, string customer_name, string reason, string notifi, int total_room)
        {
            notifi = notifi.Replace("[USER_NAME]", user.FullName);
            notifi = notifi.Replace("[RESERVATION_NUMBER]", ReservationRoomNumber.ToString());
            notifi = notifi.Replace("[CUSTOMER_NAME]", customer_name);
            notifi = notifi.Replace("[REASON]", reason);
            notifi = notifi.Replace("[TOTAL_ROOM]", total_room.ToString());
            Notification.sendNotificationToDevice(user.UserName.ToLower(), notifi, user.HotelId, "NOTIFICATION_CANCELED");
        }
        public static async Task processNotificationBookedNan(UserProfile user, int ReservationRoomNumber, string customerName, string notifi)
        {

            //NOTIFICATION_BOOKED_CONTENT
            //NOTIFICATION_BOOKED_GROUP_CONTENT
            notifi = notifi.Replace("[USER]", user.FullName);
            notifi = notifi.Replace("[RESERVATION_NUMBER]", ReservationRoomNumber.ToString());
            notifi = notifi.Replace("[FULL_NAME]", customerName);
            Notification.sendNotificationToDevice(user.UserName.ToLower(), notifi, user.HotelId, "NOTIFICATION_BOOKED");
        }

        public static async Task processNotificationUndoCancel(UserProfile user, int ReservationRoomNumber, string room_name, string customerName, string notifi)
        {

            //NOTIFICATION_BOOKED_CONTENT
            //NOTIFICATION_BOOKED_GROUP_CONTENT
            notifi = notifi.Replace("[USER]", user.FullName);
            notifi = notifi.Replace("[RESERVATION_NUMBER]", ReservationRoomNumber.ToString());
            notifi = notifi.Replace("[FULL_NAME]", customerName);
            notifi = notifi.Replace("[ROOM]", room_name);
            Notification.sendNotificationToDevice(user.UserName.ToLower(), notifi, user.HotelId, "NOTIFICATION_BOOKED");
        }

        public static async Task processNotificationUndoCancelNan(UserProfile user, int ReservationRoomNumber, string customerName, string notifi)
        {

            //NOTIFICATION_BOOKED_CONTENT
            //NOTIFICATION_BOOKED_GROUP_CONTENT
            notifi = notifi.Replace("[USER]", user.FullName);
            notifi = notifi.Replace("[RESERVATION_NUMBER]", ReservationRoomNumber.ToString());
            notifi = notifi.Replace("[FULL_NAME]", customerName); 
            Notification.sendNotificationToDevice(user.UserName.ToLower(), notifi, user.HotelId, "NOTIFICATION_BOOKED");
        }

        public static async Task processNotificationBookedCm(string user, string notifi, int HotelId)
        {
             
            Notification.sendNotificationToDevice(user, notifi, HotelId, "NOTIFICATION_BOOKED");
        }
        public static async Task processNotificationBookedGroup(UserProfile user, int? ReservationRoomNumber, string customerName, int total_room, string notifi)
        {
            notifi = notifi.Replace("[USER]", user.FullName);
            notifi = notifi.Replace("[RESERVATION_NUMBER]", ReservationRoomNumber.ToString());
            notifi = notifi.Replace("[FULL_NAME]", customerName);
            notifi = notifi.Replace("[TOTAL_ROOM]", total_room.ToString());
            Notification.sendNotificationToDevice(user.UserName.ToLower(), notifi, user.HotelId, "NOTIFICATION_BOOKED");
        }
        public static async Task processNotificationPastCheckout(UserProfile user, string RoomName, PastCheckOutModel app)
        {    
            Notification.sendNotificationToDevice(user.UserName.ToLower(), user.FullName +" "+ app.languageKeys["ALREADY_APPLY_PAST_CHECKOUT"].ToString() + " " + RoomName + " ", user.HotelId, "NOTIFICATION_PAST_CHECKOUT");
        }

        public static async Task processNotificationDiscount(ApplyDiscountModel model, UserProfile user)
        {
            var discountMessage = "";
            var context = new ezCloudDataContext();
            var currentRR = context.ReservationRooms.Where(rr => rr.HotelId == user.HotelId && rr.ReservationRoomId == model.reservationRoomId).FirstOrDefault();
            if (currentRR != null)
            {
                if (model.FOC)
                {
                    discountMessage = model.languageKeys["NOTIFICATION_FREE_OF_CHARGE"] != null ? model.languageKeys["NOTIFICATION_FREE_OF_CHARGE"].ToString() : "";
                }
                else
                {
                    discountMessage = model.languageKeys["NOTIFICATION_DISCOUNT_ROOM_PRICE"] != null ? model.languageKeys["NOTIFICATION_DISCOUNT_ROOM_PRICE"].ToString() : "";
                }

                var ReservationNumber = context.ReservationRooms.Where(rr => rr.HotelId == user.HotelId && rr.ReservationRoomId == currentRR.ReservationRoomId)
                   .Join(context.Reservations, r => r.ReservationId, p => p.ReservationId, (r, p) => new { r.Reservations.ReservationNumber }).FirstOrDefault().ReservationNumber;
                var hotel = context.Hotels.Where(h => h.HotelId == user.HotelId).FirstOrDefault();
                var money = context.Money.Where(m => m.MoneyId == hotel.DefaultMoneyId).FirstOrDefault().MoneyName;
                var roomId = context.ReservationRooms.Where(r => r.HotelId == user.HotelId && r.ReservationRoomId == currentRR.ReservationRoomId).FirstOrDefault().RoomId;
                var roomName = roomId != null ? context.Rooms.Where(r => r.HotelId == user.HotelId && r.RoomId == roomId).FirstOrDefault().RoomName : ReservationNumber.ToString();
                var room_resno = "";
                if (roomId != null)
                {
                    room_resno = model.languageKeys["ROOM"] != null ? model.languageKeys["ROOM"].ToString() : "";
                }
                else
                {
                    room_resno = model.languageKeys["RES_NO"] != null ? model.languageKeys["RES_NO"].ToString() : "";
                }

                discountMessage = discountMessage.Replace("[USER]", user.FullName);
                discountMessage = discountMessage.ToString().Replace("[ROOM]", roomName);
                discountMessage = discountMessage.ToString().Replace("[ROOM_RESNO]", room_resno);
                if (model.DiscountFlat > 0)
                {
                    var spaymentAmount = Math.Abs(Convert.ToDecimal(model.DiscountFlat)).ToString("c", Utilities.GetCurrencyFormatProviderSymbolDecimals(money));
                    discountMessage = discountMessage.ToString().Replace("[DISCOUNT_FLAT]", money + " " + spaymentAmount);
                }
                else
                {
                    discountMessage = discountMessage.ToString().Replace("[DISCOUNT_FLAT]", "");
                }

                if (model.DiscountPercentage > 0)
                {
                    discountMessage = discountMessage.ToString().Replace("[DISCOUNT_PERCENTAGE]", model.DiscountPercentage.ToString() + " %");
                }
                else
                {
                    discountMessage = discountMessage.ToString().Replace("[DISCOUNT_PERCENTAGE]", "");
                }

                if (model.DiscountFlat != 0 || model.DiscountPercentage != 0 || model.FOC)
                {
                    Notification.sendNotificationToDevice(user.UserName.ToLower(), discountMessage, user.HotelId, "NOTIFICATION_WHEN_DISCOUNT_ROOM_PRICE");
                }
            }

                
        }
         
        public static async Task processNotificationDiscountAtWalkin(SaveRoomData model, UserProfile user)
        {
            var discountMessage = "";
            var context = new ezCloudDataContext();
            //var currentRR = context.ReservationRooms.Where(rr => rr.HotelId == user.HotelId && rr.ReservationRoomId == model.reservationRoomId).FirstOrDefault();
            if (model.room.DiscountFlat > 0 || model.room.DiscountPercentage > 0)
            {
                 
                discountMessage = model.languageKeys["NOTIFICATION_DISCOUNT_ROOM_PRICE"] != null ? model.languageKeys["NOTIFICATION_DISCOUNT_ROOM_PRICE"].ToString() : "";

                var ReservationNumber = model.room.Reservations.ReservationNumber; /*context.ReservationRooms.Where(rr => rr.HotelId == user.HotelId && rr.ReservationRoomId == currentRR.ReservationRoomId)
                   .Join(context.Reservations, r => r.ReservationId, p => p.ReservationId, (r, p) => new { r.Reservations.ReservationNumber }).FirstOrDefault().ReservationNumber;*/
                var hotel = context.Hotels.Where(h => h.HotelId == user.HotelId).FirstOrDefault();
                var money = context.Money.Where(m => m.MoneyId == hotel.DefaultMoneyId).FirstOrDefault().MoneyName;
                //var roomId = context.ReservationRooms.Where(r => r.HotelId == user.HotelId && r.ReservationRoomId == currentRR.ReservationRoomId).FirstOrDefault().RoomId;
                var roomName = model.room.RoomId != null ? model.room.Rooms.RoomName.ToString(): ReservationNumber.ToString(); // context.Rooms.Where(r => r.HotelId == user.HotelId && r.RoomId == roomId).FirstOrDefault().RoomName : ReservationNumber.ToString();
                var room_resno = "";
                if (model.room.RoomId != null)
                {
                    room_resno = model.languageKeys["ROOM"] != null ? model.languageKeys["ROOM"].ToString() : "";
                }
                else
                {
                    room_resno = model.languageKeys["RES_NO"] != null ? model.languageKeys["RES_NO"].ToString() : "";
                }

                discountMessage = discountMessage.Replace("[USER]", user.FullName);
                discountMessage = discountMessage.ToString().Replace("[ROOM]", roomName);
                discountMessage = discountMessage.ToString().Replace("[ROOM_RESNO]", room_resno);
                if (model.room.DiscountFlat > 0)
                {
                    var spaymentAmount = Math.Abs(Convert.ToDecimal(model.room.DiscountFlat)).ToString("c", Utilities.GetCurrencyFormatProviderSymbolDecimals(money));
                    discountMessage = discountMessage.ToString().Replace("[DISCOUNT_FLAT]", money + " " + spaymentAmount);
                }
                else
                {
                    discountMessage = discountMessage.ToString().Replace("[DISCOUNT_FLAT]", "");
                }

                if (model.room.DiscountPercentage > 0)
                {
                    discountMessage = discountMessage.ToString().Replace("[DISCOUNT_PERCENTAGE]", model.room.DiscountPercentage.ToString() + " %");
                }
                else
                {
                    discountMessage = discountMessage.ToString().Replace("[DISCOUNT_PERCENTAGE]", "");
                }

                if ( model.room.DiscountFlat != 0 || model.room.DiscountPercentage != 0 )
                {
                    Notification.sendNotificationToDevice(user.UserName.ToLower(), discountMessage, user.HotelId, "NOTIFICATION_WHEN_DISCOUNT_ROOM_PRICE");
                }
            }


        }
         
        public static async Task processNotificationAddNewPayment(PaymentModel payments, UserProfile user) 
        {
            var context = new ezCloudDataContext();
            var paymentMessage = "";
            var payment = payments.payment;
            if (payment.PaymentTypeName == "NEW_PAYMENT")
            {
                paymentMessage = payments.languageKeys["NOTIFICATION_NEWPAYMENT"] != null ? payments.languageKeys["NOTIFICATION_NEWPAYMENT"].ToString() : "";
            }
            else if (payment.PaymentTypeName == "DEPOSIT")
            {
                paymentMessage = payments.languageKeys["NOTIFICATION_DEPOSIT"] != null ? payments.languageKeys["NOTIFICATION_DEPOSIT"].ToString() : "";
            }
            else if (payment.PaymentTypeName == "REFUND")
            {
                paymentMessage = payments.languageKeys["NOTIFICATION_REFUND"] != null ? payments.languageKeys["NOTIFICATION_REFUND"].ToString() : "";
            }
            var ReservationNumber = context.ReservationRooms.Where(rr => rr.HotelId == user.HotelId && rr.ReservationRoomId == payment.ReservationRoomId)
                .Join(context.Reservations, r => r.ReservationId, p => p.ReservationId, (r, p) => new { r.Reservations.ReservationNumber }).FirstOrDefault().ReservationNumber;
            var money = context.Money.Where(m => m.HotelId == user.HotelId && m.MoneyId == payment.MoneyId).FirstOrDefault().MoneyName;
            var paymethodname = context.PaymentMethods.Where(m => m.PaymentMethodId == payment.PaymentMethodId).FirstOrDefault().PaymentMethodName;
            var roomId = context.ReservationRooms.Where(r => r.HotelId == user.HotelId && r.ReservationRoomId == payment.ReservationRoomId).FirstOrDefault().RoomId;
            var roomName = roomId != null ? context.Rooms.Where(r => r.HotelId == user.HotelId && r.RoomId == roomId).FirstOrDefault().RoomName : ReservationNumber.ToString();
            var room_resno = "";
            if (roomId != null)
            {
                room_resno = payments.languageKeys["ROOM"] != null ? payments.languageKeys["ROOM"].ToString() : "";
            }
            else
            {
                room_resno = payments.languageKeys["RES_NO"] != null ? payments.languageKeys["RES_NO"].ToString() : "";
            }

            //var amount = Math.Abs(Convert.ToDecimal(payment.Amount));
            decimal paymentAmount = 0;
            if (payment.AmountInSpecificMoney != null)
            {
                paymentAmount = Math.Abs(Convert.ToDecimal(payment.AmountInSpecificMoney)); //(decimal)payments.payment.AmountInSpecificMoney;
            }
            else
            {
                paymentAmount = Math.Abs(Convert.ToDecimal(payment.Amount));
            }

            paymentMessage = paymentMessage.Replace("[USER]", user.FullName);

            paymentMessage = paymentMessage.ToString().Replace("[PAYMENTMETHOD]", payments.languageKeys[paymethodname] != null ? payments.languageKeys[paymethodname].ToString() : "");
            //paymentMessage = paymentMessage.ToString().Replace("[MONEY]", money + " " +Math.Abs(Convert.ToDecimal(paymentAmount)).ToString("0,0", CultureInfo.InvariantCulture));
            var spaymentAmount = Math.Abs(Convert.ToDecimal(paymentAmount)).ToString("c", Utilities.GetCurrencyFormatProviderSymbolDecimals(money));
        
            paymentMessage = paymentMessage.ToString().Replace("[MONEY]", money + " " + spaymentAmount);
            paymentMessage = paymentMessage.ToString().Replace("[ROOM]", roomName);
            paymentMessage = paymentMessage.ToString().Replace("[ROOM_RESNO]", room_resno);

            Notification.sendNotificationToDevice(user.UserName.ToLower(), paymentMessage, user.HotelId, "NOTIFICATION_WHEN_POST_PAYMENT");
        }
        public static async Task processNotificationCheckout(UserProfile user, string RoomName)
        {
            Notification.sendNotificationToDevice(user.UserName.ToLower(), user.FullName + " Checkout " + RoomName + " ", user.HotelId, "NOTIFICATION_CHECKOUT");
        }
        
        public static void processNotificationDeletePayment(PaymentModel payments, UserProfile user)
        {
            var context = new ezCloudDataContext();
            var paymentMessage = "";
            var payment = payments.payment;
            paymentMessage = payments.languageKeys["NOTIFICATION_DELETED_PAYMENT"] != null ? payments.languageKeys["NOTIFICATION_DELETED_PAYMENT"].ToString() : "";
           
            var ReservationNumber = context.ReservationRooms.Where(rr => rr.HotelId == user.HotelId && rr.ReservationRoomId == payment.ReservationRoomId)
                    .Join(context.Reservations, r => r.ReservationId, p => p.ReservationId, (r, p) => new { r.Reservations.ReservationNumber }).FirstOrDefault().ReservationNumber;
            var money = context.Money.Where(m => m.HotelId == user.HotelId && m.MoneyId == payment.MoneyId).FirstOrDefault().MoneyName;
            var paymethodname = context.PaymentMethods.Where(m => m.PaymentMethodId == payment.PaymentMethodId).FirstOrDefault().PaymentMethodName;
            var roomId = context.ReservationRooms.Where(r => r.HotelId == user.HotelId && r.ReservationRoomId == payment.ReservationRoomId).FirstOrDefault().RoomId;
            var roomName = roomId != null ? context.Rooms.Where(r => r.HotelId == user.HotelId && r.RoomId == roomId).FirstOrDefault().RoomName : ReservationNumber.ToString();
            var room_resno = "";
            if (roomId != null)
            {
                room_resno = payments.languageKeys["ROOM"] != null ? payments.languageKeys["ROOM"].ToString() : "";
            }
            else
            {
                room_resno = payments.languageKeys["RES_NO"] != null ? payments.languageKeys["RES_NO"].ToString() : "";
            }

            paymentMessage = paymentMessage.Replace("[USER]", user.FullName);
            paymentMessage = paymentMessage.ToString().Replace("[PAYMENTMETHOD]", payments.languageKeys[paymethodname] != null ? payments.languageKeys[paymethodname].ToString() : "");
            var spaymentAmount = Math.Abs(Convert.ToDecimal(payment.AmountInSpecificMoney==null?payment.Amount:payment.AmountInSpecificMoney)).ToString("c", Utilities.GetCurrencyFormatProviderSymbolDecimals(money));
            paymentMessage = paymentMessage.ToString().Replace("[MONEY]", money + " " + spaymentAmount);
            paymentMessage = paymentMessage.ToString().Replace("[ROOM]", roomName);
            paymentMessage = paymentMessage.ToString().Replace("[ROOM_RESNO]", room_resno);

            Notification.sendNotificationToDevice(user.UserName.ToLower(), paymentMessage, user.HotelId, "NOTIFICATION_WHEN_DELETE_PAYMENT");
        }
        public static void processNotificationDeleteCityLedgerPayment(PaymentModel payments, UserProfile user)
        {
            var context = new ezCloudDataContext();
            var paymentMessage = "";
            var payment = payments.payment;
            paymentMessage = payments.languageKeys["NOTIFICATION_DELETED_CITY_LEDGER_PAYMENT"] != null ? payments.languageKeys["NOTIFICATION_DELETED_CITY_LEDGER_PAYMENT"].ToString() : "";
            var money = context.Money.Where(m => m.HotelId == user.HotelId && m.MoneyId == payment.MoneyId).FirstOrDefault().MoneyName;
            var paymethodname = context.PaymentMethods.Where(m => m.PaymentMethodId == payment.PaymentMethodId).FirstOrDefault().PaymentMethodName;
            var companyName = context.Company.Where(c => c.HotelId == user.HotelId && c.CompanyId == payment.CompanyId).FirstOrDefault().CompanyName;
           
            paymentMessage = paymentMessage.Replace("[USER]", user.FullName);
            paymentMessage = paymentMessage.ToString().Replace("[PAYMENTMETHOD]", payments.languageKeys[paymethodname] != null ? payments.languageKeys[paymethodname].ToString() : "");
            var spaymentAmount = Math.Abs(Convert.ToDecimal(payment.AmountInSpecificMoney==null?payment.Amount:payment.AmountInSpecificMoney)).ToString("c", Utilities.GetCurrencyFormatProviderSymbolDecimals(money));
            paymentMessage = paymentMessage.ToString().Replace("[MONEY]", money + " " + spaymentAmount);
            paymentMessage = paymentMessage.ToString().Replace("[COMPANY]", companyName);
            Notification.sendNotificationToDevice(user.UserName.ToLower(), paymentMessage, user.HotelId, "NOTIFICATION_WHEN_DELETE_PAYMENT");
        }
        public static async Task processNotificationAddNewCityLedgerPayment(PaymentModel payments, UserProfile user)
        {
            var context = new ezCloudDataContext();
            var paymentMessage = "";
            var payment = payments.payment;
            if (payment.PaymentTypeName == "NEW_PAYMENT")
            {
                paymentMessage = payments.languageKeys["NOTIFICATION_CITY_LEDGER_NEWPAYMENT"] != null ? payments.languageKeys["NOTIFICATION_CITY_LEDGER_NEWPAYMENT"].ToString() : "";
            }
            else if (payment.PaymentTypeName == "DEPOSIT")
            {
                paymentMessage = payments.languageKeys["NOTIFICATION_DEPOSIT"] != null ? payments.languageKeys["NOTIFICATION_DEPOSIT"].ToString() : "";
            }
            else if (payment.PaymentTypeName == "REFUND")
            {
                paymentMessage = payments.languageKeys["NOTIFICATION_REFUND"] != null ? payments.languageKeys["NOTIFICATION_REFUND"].ToString() : "";
            }
            var companyName = context.Company.Where(c => c.HotelId == user.HotelId && c.CompanyId == payment.CompanyId).FirstOrDefault().CompanyName;
            var money = context.Money.Where(m => m.HotelId == user.HotelId && m.MoneyId == payment.MoneyId).FirstOrDefault().MoneyName;
            var paymethodname = context.PaymentMethods.Where(m => m.PaymentMethodId == payment.PaymentMethodId).FirstOrDefault().PaymentMethodName;
            
            decimal paymentAmount = 0;
            if (payment.AmountInSpecificMoney != null)
            {
                paymentAmount = Math.Abs(Convert.ToDecimal(payment.AmountInSpecificMoney)); //(decimal)payments.payment.AmountInSpecificMoney;
            }
            else
            {
                paymentAmount = Math.Abs(Convert.ToDecimal(payment.Amount));
            }

            paymentMessage = paymentMessage.Replace("[USER]", user.FullName);

            paymentMessage = paymentMessage.ToString().Replace("[PAYMENTMETHOD]", payments.languageKeys[paymethodname] != null ? payments.languageKeys[paymethodname].ToString() : "");
            var spaymentAmount = Math.Abs(Convert.ToDecimal(paymentAmount)).ToString("c", Utilities.GetCurrencyFormatProviderSymbolDecimals(money));
            paymentMessage = paymentMessage.ToString().Replace("[MONEY]", money + " " + spaymentAmount);
            paymentMessage = paymentMessage.ToString().Replace("[COMPANY]", companyName);

            Notification.sendNotificationToDevice(user.UserName.ToLower(), paymentMessage, user.HotelId, "NOTIFICATION_WHEN_POST_PAYMENT");
        }
        public static async Task processNotificationDeleteExtraserviceItems(deletedSelectedServiceItems item, UserProfile user, RoomExtraServiceItems oldItem)
        {
            var context = new ezCloudDataContext();
            var serviceItemList = "";
            var extraserviceMessage = "";
            extraserviceMessage = item.languageKeys["NOTIFICATION_DELETE_EXTRASERVICE"] != null ? item.languageKeys["NOTIFICATION_DELETE_EXTRASERVICE"].ToString() : "";
            //var oldItem = context.RoomExtraServiceItems.Where(p => p.HotelId == user.HotelId && p.RoomExtraServiceItemId == item.roomExtraServiceItems.RoomExtraServiceItemId).FirstOrDefault();
            if (oldItem!=null)
            {
                RoomExtraServices roomES = context.RoomExtraServices.Where(res => res.HotelId == user.HotelId && res.RoomExtraServiceId == item.roomExtraServiceItems.RoomExtraServiceId).FirstOrDefault();
                roomES.Amount -= oldItem.Quantity * oldItem.Price;
                serviceItemList = serviceItemList + oldItem.ExtraServiceItems.ExtraServiceItemName + "(" + oldItem.Quantity.ToString() + ") ";
            }
            var ReservationNumber = context.ReservationRooms.Where(rr => rr.HotelId == user.HotelId && rr.ReservationRoomId == oldItem.ReservationRoomId)
                   .Join(context.Reservations, r => r.ReservationId, p => p.ReservationId, (r, p) => new { r.Reservations.ReservationNumber }).FirstOrDefault().ReservationNumber;
            var roomId = context.ReservationRooms.Where(r => r.HotelId == user.HotelId && r.ReservationRoomId == oldItem.ReservationRoomId).FirstOrDefault().RoomId;
            var roomName = roomId != null ? context.Rooms.Where(r => r.HotelId == user.HotelId && r.RoomId == roomId).FirstOrDefault().RoomName : ReservationNumber.ToString();
            var room_resno = "";
            if (roomId != null)
            {
                room_resno = item.languageKeys["ROOM"] != null ? item.languageKeys["ROOM"].ToString() : "";
            }
            else
            {
                room_resno = item.languageKeys["RES_NO"] != null ? item.languageKeys["RES_NO"].ToString() : "";
            }

            extraserviceMessage = extraserviceMessage.Replace("[USER]", user.FullName);
            extraserviceMessage = extraserviceMessage.ToString().Replace("[ROOM]", roomName);
            extraserviceMessage = extraserviceMessage.ToString().Replace("[ROOM_RESNO]", room_resno);
            extraserviceMessage = extraserviceMessage + " : " + serviceItemList;

            Notification.sendNotificationToDevice(user.UserName.ToLower(), extraserviceMessage, user.HotelId, "NOTIFICATION_WHEN_DELETE_EXTRASERVICE");
        }
        public static async Task processNotificationDeleteExtraService(deletedSelectedServices res, UserProfile user, RoomExtraServices oldRES)
        {
            var extraserviceMessage = "";
            extraserviceMessage = res.languageKeys["NOTIFICATION_DELETE_EXTRASERVICE"] != null ? res.languageKeys["NOTIFICATION_DELETE_EXTRASERVICE"].ToString() : "";
            var context = new ezCloudDataContext();
            //var oldRES = context.RoomExtraServices.Where(p => p.HotelId == user.HotelId && p.RoomExtraServiceId == res.roomExtraServices.RoomExtraServiceId).FirstOrDefault();
            var serviceItemList = "";
            if (oldRES != null)
            {  
                var defaultMoneyId = context.Hotels.Where(h => h.HotelId == user.HotelId).FirstOrDefault().DefaultMoneyId;
                var money = context.Money.Where(m => m.HotelId == user.HotelId && m.MoneyId == defaultMoneyId).FirstOrDefault().MoneyName;
                if (money == null) money = "VND";
                var spaymentAmount = Math.Abs(Convert.ToDecimal(res.roomExtraServices.Amount)).ToString("c", Utilities.GetCurrencyFormatProviderSymbolDecimals(money));
                serviceItemList = serviceItemList + res.roomExtraServices.RoomExtraServiceDescription + " (" + money + " " + spaymentAmount + ") ";
            }

            var ReservationNumber = context.ReservationRooms.Where(rr => rr.HotelId == user.HotelId && rr.ReservationRoomId == oldRES.ReservationRoomId)
                   .Join(context.Reservations, r => r.ReservationId, p => p.ReservationId, (r, p) => new { r.Reservations.ReservationNumber }).FirstOrDefault().ReservationNumber;
            var roomId = context.ReservationRooms.Where(r => r.HotelId == user.HotelId && r.ReservationRoomId == oldRES.ReservationRoomId).FirstOrDefault().RoomId;
            var roomName = roomId != null ? context.Rooms.Where(r => r.HotelId == user.HotelId && r.RoomId == roomId).FirstOrDefault().RoomName : ReservationNumber.ToString();
            var room_resno = "";
            if (roomId != null)
            {
                room_resno = res.languageKeys["ROOM"] != null ? res.languageKeys["ROOM"].ToString() : "";
            }
            else
            {
                room_resno = res.languageKeys["RES_NO"] != null ? res.languageKeys["RES_NO"].ToString() : "";
            }

            extraserviceMessage = extraserviceMessage.Replace("[USER]", user.FullName);
            extraserviceMessage = extraserviceMessage.ToString().Replace("[ROOM]", roomName);
            extraserviceMessage = extraserviceMessage.ToString().Replace("[ROOM_RESNO]", room_resno);
            extraserviceMessage = extraserviceMessage + " : " + serviceItemList;

            Notification.sendNotificationToDevice(user.UserName.ToLower(), extraserviceMessage, user.HotelId, "NOTIFICATION_WHEN_DELETE_EXTRASERVICE");
        }
        public static async Task processNotificationPreCheckin(Controllers.RoomController.ChangeReservationStatusModel model, UserProfile user, ReservationRooms currentRR)
        {
            var preMessage = "";
            var context = new ezCloudDataContext();
            preMessage = model.languageKeys["NOTIFICATION_PRE_CHẸCKIN"] != null ? model.languageKeys["NOTIFICATION_PRE_CHẸCKIN"].ToString() : "";
            var ReservationNumber = context.ReservationRooms.Where(rr => rr.HotelId == user.HotelId && rr.ReservationRoomId == currentRR.ReservationRoomId)
                   .Join(context.Reservations, r => r.ReservationId, p => p.ReservationId, (r, p) => new { r.Reservations.ReservationNumber }).FirstOrDefault().ReservationNumber;
            var roomId = context.ReservationRooms.Where(r => r.HotelId == user.HotelId && r.ReservationRoomId == currentRR.ReservationRoomId).FirstOrDefault().RoomId;
            var roomName = roomId != null ? context.Rooms.Where(r => r.HotelId == user.HotelId && r.RoomId == roomId).FirstOrDefault().RoomName : ReservationNumber.ToString();
            var room_resno = "";
            if (roomId != null)
            {
                room_resno = model.languageKeys["ROOM"] != null ? model.languageKeys["ROOM"].ToString() : "";
            }
            else
            {
                room_resno = model.languageKeys["RES_NO"] != null ? model.languageKeys["RES_NO"].ToString() : "";
            }

            preMessage = preMessage.Replace("[USER]", user.FullName);
            preMessage = preMessage.ToString().Replace("[ROOM]", roomName);
            preMessage = preMessage.ToString().Replace("[ROOM_RESNO]", room_resno);
            Notification.sendNotificationToDevice(user.UserName.ToLower(), preMessage, user.HotelId, "NOTIFICATION_WHEN_PRE_CHECKIN");
        }
        public static async Task processNotificationPreCheckout(Controllers.RoomController.ChangeReservationStatusModel model, UserProfile user, ReservationRooms currentRR)
        {
            var preMessage = "";
            var context = new ezCloudDataContext();
            preMessage = model.languageKeys["NOTIFICATION_PRE_CHẸCKOUT"] != null ? model.languageKeys["NOTIFICATION_PRE_CHẸCKOUT"].ToString() : "";
            var ReservationNumber = context.ReservationRooms.Where(rr => rr.HotelId == user.HotelId && rr.ReservationRoomId == currentRR.ReservationRoomId)
                    .Join(context.Reservations, r => r.ReservationId, p => p.ReservationId, (r, p) => new { r.Reservations.ReservationNumber }).FirstOrDefault().ReservationNumber;
            var roomId = context.ReservationRooms.Where(r => r.HotelId == user.HotelId && r.ReservationRoomId == currentRR.ReservationRoomId).FirstOrDefault().RoomId;
            var roomName = roomId != null ? context.Rooms.Where(r => r.HotelId == user.HotelId && r.RoomId == roomId).FirstOrDefault().RoomName : ReservationNumber.ToString();
            var room_resno = "";
            if (roomId != null)
            {
                room_resno = model.languageKeys["ROOM"] != null ? model.languageKeys["ROOM"].ToString() : "";
            }
            else
            {
                room_resno = model.languageKeys["RES_NO"] != null ? model.languageKeys["RES_NO"].ToString() : "";
            }

            preMessage = preMessage.Replace("[USER]", user.FullName);
            preMessage = preMessage.ToString().Replace("[ROOM]", roomName);
            preMessage = preMessage.ToString().Replace("[ROOM_RESNO]", room_resno);
            Notification.sendNotificationToDevice(user.UserName.ToLower(), preMessage, user.HotelId, "NOTIFICATION_WHEN_PRE_CHECKOUT");
        }
        public static async Task processNotificationRoomMove(RoomMoveModel model, UserProfile currentClientUser, ReservationRooms oldRR)
        {
           
            var moveRoomMessage = "";
            moveRoomMessage = model.languageKeys["NOTIFICATION_CHANGE_ROOM"] != null ? model.languageKeys["NOTIFICATION_CHANGE_ROOM"].ToString() : "";
          
            var context = new ezCloudDataContext();
            if (oldRR != null)
            {
                //ReservationRooms orgOldRR = oldRR.; // for process CMS 
                var arrivalDate = oldRR.ArrivalDate;
                var departureDate = oldRR.DepartureDate;
                var roomTypeId = oldRR.RoomTypeId;

              
                Rooms oldRoom = context.Rooms.Where(or => or.HotelId == currentClientUser.HotelId && or.RoomId == oldRR.RoomId).FirstOrDefault();

                if (oldRR.BookingStatus == "CHECKIN")
                {
                    Rooms newRoom = context.Rooms.Where(or => or.HotelId == currentClientUser.HotelId && or.RoomId == model.NewRoomId).FirstOrDefault();
                    moveRoomMessage = moveRoomMessage.Replace("[USER]", currentClientUser.FullName);
                    moveRoomMessage = moveRoomMessage.Replace("[OLD_ROOM]", oldRoom.RoomName);
                    moveRoomMessage = moveRoomMessage.Replace("[NEW_ROOM]", newRoom.RoomName);

                    Notification.sendNotificationToDevice(currentClientUser.UserName.ToLower(), moveRoomMessage, currentClientUser.HotelId, "NOTIFICATION_WHEN_CHANGE_ROOM");
                }

              
            }
            
        }
        public static async Task processNotificationCreateExtraService(Controllers.RoomController.postedSelectedServiceItems items, UserProfile user, ReservationRooms reservation)
        {
            var extraserviceMessage = "";
            extraserviceMessage = items.languageKeys["NOTIFICATION_POST_EXTRASERVICE"] != null ? items.languageKeys["NOTIFICATION_POST_EXTRASERVICE"].ToString() : "";
           
            var context = new ezCloudDataContext();
            decimal totalMoney = 0; decimal SumtotalMoney = 0;
            var serviceItemList = "";
            foreach (Controllers.RoomController.SelectedServiceItem item in items.items)
            {
                var realItem = context.ExtraServiceItems.Where(it => it.HotelId == user.HotelId && it.ExtraServiceItemId == item.item.ExtraServiceItemId).FirstOrDefault();
                if (realItem != null)
                {
                    totalMoney += (decimal)realItem.Price * item.quantity;
                    serviceItemList = serviceItemList + realItem.ExtraServiceItemName + "(" + item.quantity.ToString() + ") ";
                }
            }
            SumtotalMoney += totalMoney;

            var ReservationNumber = context.ReservationRooms.Where(rr => rr.HotelId == user.HotelId && rr.ReservationRoomId == reservation.ReservationRoomId)
                   .Join(context.Reservations, r => r.ReservationId, p => p.ReservationId, (r, p) => new { r.Reservations.ReservationNumber }).FirstOrDefault().ReservationNumber;
            var roomId = context.ReservationRooms.Where(r => r.HotelId == user.HotelId && r.ReservationRoomId == reservation.ReservationRoomId).FirstOrDefault().RoomId;
            var roomName = roomId != null ? context.Rooms.Where(r => r.HotelId == user.HotelId && r.RoomId == roomId).FirstOrDefault().RoomName : ReservationNumber.ToString();
            var room_resno = "";
            if (roomId != null)
            {
                room_resno = items.languageKeys["ROOM"] != null ? items.languageKeys["ROOM"].ToString() : "";
            }
            else
            {
                room_resno = items.languageKeys["RES_NO"] != null ? items.languageKeys["RES_NO"].ToString() : "";
            }
            var defaultMoneyId = context.Hotels.Where(h => h.HotelId == user.HotelId).FirstOrDefault().DefaultMoneyId;
            var money = context.Money.Where(m => m.HotelId == user.HotelId && m.MoneyId == defaultMoneyId).FirstOrDefault().MoneyName;
            if (money == null) money = "VND";
            var spaymentAmount = Math.Abs(Convert.ToDecimal(SumtotalMoney)).ToString("c", Utilities.GetCurrencyFormatProviderSymbolDecimals(money));
            extraserviceMessage = extraserviceMessage.Replace("[USER]", user.FullName);
            extraserviceMessage = extraserviceMessage.ToString().Replace("[ROOM]", roomName);
            extraserviceMessage = extraserviceMessage.ToString().Replace("[ROOM_RESNO]", room_resno);
            extraserviceMessage = extraserviceMessage + " : " + serviceItemList + " (" + money + " " + spaymentAmount + ")";

            Notification.sendNotificationToDevice(user.UserName.ToLower(), extraserviceMessage, user.HotelId, "NOTIFICATION_WHEN_POST_EXTRASERVICE");
        }
        public static async Task processNotificationCreateExtraServiceNoItem(Controllers.RoomController.ExtraServiceNoItemModel model, UserProfile user, ReservationRooms reservation)
        {
            var extraserviceMessage = "";
            extraserviceMessage = model.languageKeys["NOTIFICATION_POST_EXTRASERVICE"] != null ? model.languageKeys["NOTIFICATION_POST_EXTRASERVICE"].ToString() : "";
            
            var context = new ezCloudDataContext();

            var ReservationNumber = context.ReservationRooms.Where(rr => rr.HotelId == user.HotelId && rr.ReservationRoomId == reservation.ReservationRoomId)
                   .Join(context.Reservations, r => r.ReservationId, p => p.ReservationId, (r, p) => new { r.Reservations.ReservationNumber }).FirstOrDefault().ReservationNumber;
            var roomId = context.ReservationRooms.Where(r => r.HotelId == user.HotelId && r.ReservationRoomId == reservation.ReservationRoomId).FirstOrDefault().RoomId;
            var roomName = roomId != null ? context.Rooms.Where(r => r.HotelId == user.HotelId && r.RoomId == roomId).FirstOrDefault().RoomName : ReservationNumber.ToString();
            var room_resno = "";
            if (roomId != null)
            {
                room_resno = model.languageKeys["ROOM"] != null ? model.languageKeys["ROOM"].ToString() : "";
            }
            else
            {
                room_resno = model.languageKeys["RES_NO"] != null ? model.languageKeys["RES_NO"].ToString() : "";
            }

            extraserviceMessage = extraserviceMessage.Replace("[USER]", user.FullName);
            extraserviceMessage = extraserviceMessage.ToString().Replace("[ROOM]", roomName);
            extraserviceMessage = extraserviceMessage.ToString().Replace("[ROOM_RESNO]", room_resno);
            var defaultMoneyId = context.Hotels.Where(h => h.HotelId == user.HotelId).FirstOrDefault().DefaultMoneyId;
            var money = context.Money.Where(m => m.HotelId == user.HotelId && m.MoneyId == defaultMoneyId).FirstOrDefault().MoneyName;
            if (money == null) money = "VND";
            var spaymentAmount = Math.Abs(Convert.ToDecimal(model.Amount)).ToString("c", Utilities.GetCurrencyFormatProviderSymbolDecimals(money));
            //extraserviceMessage = extraserviceMessage + " : " + model.RoomExtraServiceDescription + "(" + Math.Abs(Convert.ToDecimal(model.Amount)).ToString("0,0", CultureInfo.InvariantCulture) + ")";

            extraserviceMessage = extraserviceMessage + " : " + model.RoomExtraServiceDescription + "(" + money + " " + spaymentAmount + ")";

            Notification.sendNotificationToDevice(user.UserName.ToLower(), extraserviceMessage, user.HotelId, "NOTIFICATION_WHEN_POST_EXTRASERVICE");
        }
        public static async Task processNotificationEditPrice(EditPriceModel model, UserProfile currentClientUser, ReservationRooms currentRR)
        {
            var context = new ezCloudDataContext();
            var editPriceMessage = "";
            editPriceMessage = model.languageKeys["NOTIFICATION_WHEN_CHANGE_PRICE"] != null ? model.languageKeys["NOTIFICATION_WHEN_CHANGE_PRICE"].ToString() : "";

            var ReservationNumber = context.ReservationRooms.Where(rr => rr.HotelId == currentClientUser.HotelId && rr.ReservationRoomId == currentRR.ReservationRoomId)
                   .Join(context.Reservations, r => r.ReservationId, p => p.ReservationId, (r, p) => new { r.Reservations.ReservationNumber }).FirstOrDefault().ReservationNumber;
            var roomId = context.ReservationRooms.Where(r => r.HotelId == currentClientUser.HotelId && r.ReservationRoomId == currentRR.ReservationRoomId).FirstOrDefault().RoomId;
            var roomName = roomId != null ? context.Rooms.Where(r => r.HotelId == currentClientUser.HotelId && r.RoomId == roomId).FirstOrDefault().RoomName : ReservationNumber.ToString();
            var room_resno = "";
            if (roomId != null)
            {
                room_resno = model.languageKeys["ROOM"] != null ? model.languageKeys["ROOM"].ToString() : "";
            }
            else
            {
                room_resno = model.languageKeys["RES_NO"] != null ? model.languageKeys["RES_NO"].ToString() : "";
            }

            var defaultMoneyId = context.Hotels.Where(h => h.HotelId == currentClientUser.HotelId).FirstOrDefault().DefaultMoneyId;
            var money = context.Money.Where(m => m.HotelId == currentClientUser.HotelId && m.MoneyId == defaultMoneyId).FirstOrDefault().MoneyName;
            if (money == null) money = "VND";

            editPriceMessage = editPriceMessage.Replace("[USER]", currentClientUser.FullName);
            editPriceMessage = editPriceMessage.ToString().Replace("[ROOM]", roomName);
            editPriceMessage = editPriceMessage.ToString().Replace("[ROOM_RESNO]", room_resno);
            var spaymentAmount = Math.Abs(Convert.ToDecimal(currentRR.Price)).ToString("c", Utilities.GetCurrencyFormatProviderSymbolDecimals(money));
            editPriceMessage = editPriceMessage.ToString().Replace("[OLD_PRICE]", spaymentAmount);

            //editPriceMessage = editPriceMessage.ToString().Replace("[OLD_PRICE]", Math.Abs(Convert.ToDecimal(currentRR.Price)).ToString("0,0", CultureInfo.InvariantCulture));
            //editPriceMessage = editPriceMessage.ToString().Replace("[NEW_PRICE]", Math.Abs(Convert.ToDecimal(model.NewPrice)).ToString("0,0", CultureInfo.InvariantCulture));
            spaymentAmount = Math.Abs(Convert.ToDecimal(model.NewPrice)).ToString("c", Utilities.GetCurrencyFormatProviderSymbolDecimals(money));
            editPriceMessage = editPriceMessage.ToString().Replace("[NEW_PRICE]", money + " " + spaymentAmount);

            Notification.sendNotificationToDevice(currentClientUser.UserName.ToLower(), editPriceMessage, currentClientUser.HotelId, "NOTIFICATION_CHANGE_PRICE");

        }

        public static async Task processNotificationSaveRoomCharge(EditRoomChargeModel model, UserProfile currentClientUser, RoomCharges currentRC)
        {

            var context = new ezCloudDataContext();
            //var currentRR = context.ReservationRooms.Where(r => r.HotelId == currentClientUser.HotelId && r.ReservationRoomId == model.ReservationRoomId).FirstOrDefault();
            var editPriceMessage = "";
            editPriceMessage = model.languageKeys["NOTIFICATION_WHEN_CHANGE_PRICE_FULLDAY"] != null ? model.languageKeys["NOTIFICATION_WHEN_CHANGE_PRICE_FULLDAY"].ToString() : "";

            var ReservationNumber = context.ReservationRooms.Where(rr => rr.HotelId == currentClientUser.HotelId && rr.ReservationRoomId == model.ReservationRoomId)
                   .Join(context.Reservations, r => r.ReservationId, p => p.ReservationId, (r, p) => new { r.Reservations.ReservationNumber }).FirstOrDefault().ReservationNumber;
            var roomId = context.ReservationRooms.Where(r => r.HotelId == currentClientUser.HotelId && r.ReservationRoomId == model.ReservationRoomId).FirstOrDefault().RoomId;
            var roomName = roomId != null ? context.Rooms.Where(r => r.HotelId == currentClientUser.HotelId && r.RoomId == roomId).FirstOrDefault().RoomName : ReservationNumber.ToString();
            var room_resno = "";
            if (roomId != null)
            {
                room_resno = model.languageKeys["ROOM"] != null ? model.languageKeys["ROOM"].ToString() : "";
            }
            else
            {
                room_resno = model.languageKeys["RES_NO"] != null ? model.languageKeys["RES_NO"].ToString() : "";
            }

            var defaultMoneyId = context.Hotels.Where(h => h.HotelId == currentClientUser.HotelId).FirstOrDefault().DefaultMoneyId;
            var money = context.Money.Where(m => m.HotelId == currentClientUser.HotelId && m.MoneyId == defaultMoneyId).FirstOrDefault().MoneyName;
            if (money == null) money = "VND";

            editPriceMessage = editPriceMessage.Replace("[USER]", currentClientUser.FullName);
            editPriceMessage = editPriceMessage.ToString().Replace("[ROOM]", roomName);
            editPriceMessage = editPriceMessage.ToString().Replace("[ROOM_RESNO]", room_resno);
            editPriceMessage = editPriceMessage.ToString().Replace("[DATE]", currentRC.StartDate.Value.Date.ToString("dd/MM/yyyy"));
            var spaymentAmount = Math.Abs(Convert.ToDecimal(currentRC.Amount)).ToString("c", Utilities.GetCurrencyFormatProviderSymbolDecimals(money));
            editPriceMessage = editPriceMessage.ToString().Replace("[OLD_PRICE]", spaymentAmount);

            //editPriceMessage = editPriceMessage.ToString().Replace("[OLD_PRICE]", Math.Abs(Convert.ToDecimal(currentRR.Price)).ToString("0,0", CultureInfo.InvariantCulture));
            //editPriceMessage = editPriceMessage.ToString().Replace("[NEW_PRICE]", Math.Abs(Convert.ToDecimal(model.NewPrice)).ToString("0,0", CultureInfo.InvariantCulture));
            spaymentAmount = Math.Abs(Convert.ToDecimal(model.Amount)).ToString("c", Utilities.GetCurrencyFormatProviderSymbolDecimals(money));
            editPriceMessage = editPriceMessage.ToString().Replace("[NEW_PRICE]", money + " " + spaymentAmount);

            Notification.sendNotificationToDevice(currentClientUser.UserName.ToLower(), editPriceMessage, currentClientUser.HotelId, "NOTIFICATION_CHANGE_PRICE");

        }

        public static async Task processNotificationSaveListRoomCharge(List<EditRoomChargeModel> models, UserProfile currentClientUser, List<RoomCharges> listCurrentRC)
        {

            var context = new ezCloudDataContext();
            var editPriceMessage = "";
            var defaultMoneyId = context.Hotels.Where(h => h.HotelId == currentClientUser.HotelId).FirstOrDefault().DefaultMoneyId;
            var money = context.Money.Where(m => m.HotelId == currentClientUser.HotelId && m.MoneyId == defaultMoneyId).FirstOrDefault().MoneyName;
            if (money == null) money = "VND";

            if (models!=null && models.Count>0)
            {
                var model = models[0];
                editPriceMessage = model.languageKeys["LIST_NOTIFICATION_WHEN_CHANGE_PRICE_FULLDAY"] != null ? model.languageKeys["LIST_NOTIFICATION_WHEN_CHANGE_PRICE_FULLDAY"].ToString() : ""+" ";

                var ReservationNumber = context.ReservationRooms.Where(rr => rr.HotelId == currentClientUser.HotelId && rr.ReservationRoomId == model.ReservationRoomId)
                       .Join(context.Reservations, r => r.ReservationId, p => p.ReservationId, (r, p) => new { r.Reservations.ReservationNumber }).FirstOrDefault().ReservationNumber;
                var roomId = context.ReservationRooms.Where(r => r.HotelId == currentClientUser.HotelId && r.ReservationRoomId == model.ReservationRoomId).FirstOrDefault().RoomId;
                var roomName = roomId != null ? context.Rooms.Where(r => r.HotelId == currentClientUser.HotelId && r.RoomId == roomId).FirstOrDefault().RoomName : ReservationNumber.ToString();
                var room_resno = "";
                if (roomId != null)
                {
                    room_resno = model.languageKeys["ROOM"] != null ? model.languageKeys["ROOM"].ToString() : "";
                }
                else
                {
                    room_resno = model.languageKeys["RES_NO"] != null ? model.languageKeys["RES_NO"].ToString() : "";
                }



                editPriceMessage = editPriceMessage.Replace("[USER]", currentClientUser.FullName);
                editPriceMessage = editPriceMessage.ToString().Replace("[ROOM]", roomName);
                editPriceMessage = editPriceMessage.ToString().Replace("[ROOM_RESNO]", room_resno);

            }
          
            foreach (var model in models)
            {
                var currentRC = listCurrentRC.Where(rc => rc.RoomChargeId == model.RoomChargeId).FirstOrDefault();
                if (currentRC!=null && currentRC.Amount!=model.Amount)
                {
                    var tempeditPriceMessage = ";[DATE]: [OLD_PRICE]->[NEW_PRICE]";
                    tempeditPriceMessage = tempeditPriceMessage.ToString().Replace("[DATE]", currentRC.StartDate.Value.Date.ToString("dd/MM"));
                    var spaymentAmount = Math.Abs(Convert.ToDecimal(currentRC.Amount)).ToString("c", Utilities.GetCurrencyFormatProviderSymbolDecimals(money));
                    tempeditPriceMessage = tempeditPriceMessage.ToString().Replace("[OLD_PRICE]", spaymentAmount);
                    spaymentAmount = Math.Abs(Convert.ToDecimal(model.Amount)).ToString("c", Utilities.GetCurrencyFormatProviderSymbolDecimals(money));
                    tempeditPriceMessage = tempeditPriceMessage.ToString().Replace("[NEW_PRICE]", money + " " + spaymentAmount);

                    editPriceMessage += tempeditPriceMessage;
                }
               
            }
            

            Notification.sendNotificationToDevice(currentClientUser.UserName.ToLower(), editPriceMessage, currentClientUser.HotelId, "NOTIFICATION_CHANGE_PRICE");

        }

        public static async Task processNotificationPOSAddNewPayment(Controllers.POSController.POSModel payments,  int  POSPaymentNumber, UserProfile user)
        {
            var context = new ezCloudDataContext();
            var currentHotel = context.Hotels.Where(h => h.HotelId == user.HotelId).FirstOrDefault();
            decimal paymentAmount = 0;
            if (currentHotel != null)
            {
                var payment = payments;
                foreach (var item in payment.Charges)
                {
                    if (item.Type == "EXTRA_SERVICE_ITEM")
                    {
                        paymentAmount += item.Price * item.Quantity;
                    }
                    else
                    {
                        paymentAmount += item.Price * item.Quantity;
                        
                    }
                }
                paymentAmount = paymentAmount -(decimal) payment.DiscountAmount;

                var paymentMessage = "";
               
                paymentMessage = payments.languageKeys["POS_NOTIFICATION_ADDNEW_INVOICE_MESSAGE"] != null ? payments.languageKeys["POS_NOTIFICATION_ADDNEW_INVOICE_MESSAGE"].ToString() : "";
                var money = currentHotel.MoneyList.Where(m => m.HotelId == user.HotelId && m.MoneyId == currentHotel.DefaultMoneyId).FirstOrDefault().MoneyName;
                paymentMessage = paymentMessage.Replace("[USER]", user.FullName);
                var spaymentAmount = Math.Abs(Convert.ToDecimal(paymentAmount)).ToString("c", Utilities.GetCurrencyFormatProviderSymbolDecimals(money));
                paymentMessage = paymentMessage.ToString().Replace("[MONEY]", money + " " + spaymentAmount);
                paymentMessage = paymentMessage.ToString().Replace("[INVOICENO]", POSPaymentNumber.ToString());
                Notification.sendNotificationToDevice(user.UserName.ToLower(), paymentMessage, user.HotelId, "POS_NOTIFICATION_ADDNEW_INVOICE");
            }
           
        }

        public static async Task processNotificationPOSDeleteInvoice(Controllers.POSController.DeleteInvoiceModel model, decimal paymentAmount,int  POSPaymentNumber , UserProfile user)
        {
            var context = new ezCloudDataContext();
            var currentHotel = context.Hotels.Where(h => h.HotelId == user.HotelId).FirstOrDefault();
           
            if (currentHotel != null)
            {
               
                var paymentMessage = "";

                paymentMessage = model.languageKeys["POS_NOTIFICATION_DELETE_INVOICE_MESSAGE"] != null ? model.languageKeys["POS_NOTIFICATION_DELETE_INVOICE_MESSAGE"].ToString() : "";
                var money = currentHotel.MoneyList.Where(m => m.HotelId == user.HotelId && m.MoneyId == currentHotel.DefaultMoneyId).FirstOrDefault().MoneyName;
                paymentMessage = paymentMessage.Replace("[USER]", user.FullName);
                var spaymentAmount = Math.Abs(Convert.ToDecimal(paymentAmount)).ToString("c", Utilities.GetCurrencyFormatProviderSymbolDecimals(money));
                paymentMessage = paymentMessage.ToString().Replace("[MONEY]", money + " " + spaymentAmount);
                paymentMessage = paymentMessage.ToString().Replace("[INVOICENO]", POSPaymentNumber.ToString());
                paymentMessage = paymentMessage.ToString().Replace("[REASON]", model.DeleteReason);
                Notification.sendNotificationToDevice(user.UserName.ToLower(), paymentMessage, user.HotelId, "POS_NOTIFICATION_DELETE_INVOICE");
            }

        }
        //public static async Task<IHttpActionResult> getNotification(string uid, int size, int from)
        //{

        //    List<Notification> lNoti = new List<Notification>();
        //    if (uid != null)
        //    {
        //        using (var client = new HttpClient())
        //        {
        //            if (size == null)
        //            {
        //                size = 10;
        //            }
        //            if (from == null)
        //            {
        //                from = 0;
        //            }
        //            // New code:
        //            client.BaseAddress = new Uri(ConfigurationManager.AppSettings["notification_server"]);
        //            client.DefaultRequestHeaders.Accept.Clear();
        //            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
        //            client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "key=" + ConfigurationManager.AppSettings["notification_server_key"]);

        //            var postData = new
        //            {
        //                uid = uid,
        //                size = size,
        //                from = from 
        //            };
        //            HttpResponseMessage response = await client.PostAsJsonAsync("messages/" + ConfigurationManager.AppSettings["notification_server_clientid"], postData);
        //            if (response.IsSuccessStatusCode)
        //            {
        //                return response.Content;
        //            }

        //            return null;
        //        }

        //    }
        //}


    }
    public class noti
    {
        public string uid { set; get; }
        public IEnumerable<DataMessage> data{ set; get; }
        public DateTime date { set; get; }
        public string message_id { set; get; }
    }
    public class DataMessage
    {
        public string message { set; get; }
        public string HotelAppCodeName { set; get; }
    }
}